// import wsmsg from "./messages"
//var _url = "ws://ws.flcrotu.cn/websocket"
var _url = "wss://ws.qtglobal.net/websocket"
//var _url = "wss://wss.vvbtc.com/websocket"
var requestId = 1;
var onMsg = null;
var wsConnection = null;
//var wsmsg = {};
wsmsg.addRequestId = function (obj) {
    if (requestId == Number.MAX_SAFE_INTEGER)
        requestId = 0;
    else
        requestId++;
    obj['requestId'] = requestId;
    return obj;
};
wsmsg.setOnWsMsg = function (onmsg) {
    onMsg = onmsg;
};
var waitConnect = [];
wsmsg.getWsConnection = function () {
    var d = new $.Deferred();
  if (wsConnection == null || wsConnection.readyState >= 2) {
    window.WebSocket = window.WebSocket || window.MozWebSocket;
    wsConnection = new WebSocket(_url);
    wsConnection.binaryType = "arraybuffer";
    wsConnection.onmessage = function (message) {
        var msg = wsmsg.ResponseMessage.decode(new Uint8Array(message.data));
        for ( var k in msg) {
            if (msg[k]) {
                msg = msg[k];
                break;
            }
        }
        if (onMsg)
			    onMsg(msg);
      };
    wsConnection.onclose = function() {
      console.log("websocket断开了");
      wsConnection = null;
      wsmsg.getWsConnection().done(function (conn) {
        vm.resetWsData();
      })
      
    }

    wsConnection.onopen = function() {
        // 通知所有等待
        for (var i = 0; i < waitConnect.length; i++)
            waitConnect[i].resolve(wsConnection);
        waitConnect = [];
        //wsmsg.heartCheck.start();
    };
  }
  if (wsConnection.readyState == 1) {
    d.resolve(wsConnection);
       //Promise.resolve(t);
  } else 
    waitConnect.push(d);
  return d.promise();
};
wsmsg.sendWsMsg = function (msg) {
  try {
    msg.lang = global_lang ; 
  } catch (e) {
    msg.lang = "SC" ; //默认简体中文
  }
  wsmsg.getWsConnection().done(function (conn) {
      conn.send(wsmsg.RequestMessage.encode(wsmsg.RequestMessage.create(msg)).finish()); 
  })
}
wsmsg.close = function() {
  console.log("websocket断开了11111");
  wsConnection.close();
  wsConnection = null;
}
let vm = null;

wsmsg.sendThis = ( _this )=> {
    vm = _this;
};
var win$ = wsmsg;
export default win$
